<!DOCTYPE html>
<html>

<head>
    <meta charset="UTF-8">
    <title>募捐详情</title>

    <link rel="stylesheet" href="../../element/element.css">
    <script src="../../element/vue.js"></script>
    <script src="../../element/index.js"></script>
    <script src="../../js/axios.min.js"></script>


</head>
<link rel="stylesheet" type="text/css" href="../../css/dontions.css">

<body>

    <body>
        <div id="app">
            <el-card>
                <el-button type="primary" @click="save()">返回</el-button>
                <h2 slot="header" style="text-align: center;">募捐详情</h2>
                <div style="display: flex; justify-content: right;">
                    <div style="display: flex; justify-content: right;">
                        <el-button type="primary" icon="el-icon-arrow-left" style="margin-right: auto;"
                            @click="goToPreviousPage">上一页</el-button>
                        <el-button type="primary" @click="goToNextPage">下一页<i
                                class="el-icon-arrow-right el-icon--right"></i></el-button>
                    </div>
                </div>
                <div v-for="detail in donationDetails" :key="detail.id">
                    <el-row>
                        <el-col :span="12">
                            <img :src="`http://${detail.donationImage}`" alt="募捐图片" width="300px" height="300px">
                            <p>&nbsp&nbsp&nbsp别名：{{ detail.alias }}&nbsp&nbsp&nbsp年龄：{{ detail.age }} </p>

                            <el-button type="primary" @click="showTable">查看信息材料</el-button>
                            <!-- 捐款对话框 -->
                            <el-button type="primary" @click="openEvaluationDialog">评价</el-button>
                        </el-col>
                        <el-col :span="12">
                            <p>目标金额：{{ detail.donationAmount }}</p>
                            <p>募捐金额原因：{{ detail.amountReason }}</p>
                            <p>截止日期：{{ detail.deadline }}</p>
                            <p>募捐时间原因:{{ detail.timeReason }}</p>
                        </el-col>
                    </el-row>
                </div>
                <el-row v-if="donationsInfo">
                    <el-col :span="24">
                        <p>申请缘由：{{ donationsInfo.incident }}</p>
                        <p>家庭情况：{{ donationsInfo.family }}</p>
                        <p>财务状况：{{ donationsInfo.finance }}</p>
                        <p>预期目标：{{ donationsInfo.status }}</p>
                    </el-col>
                </el-row>
                <!-- 积分表认证 -->
                <h3 style="text-align: center">积分认证情况</h3>
                <el-table :data="pointsList" style="width: 100%" @selection-change="onSelectionChange">
                    <!-- 选择列 -->
                    <!-- 其他列 -->
                    <el-table-column prop="pointsRulesId" label="ID"></el-table-column>
                    <el-table-column prop="ruleTitle" label="标题"></el-table-column>
                    <el-table-column prop="pointsValue" label="分值"></el-table-column>
                    <el-table-column prop="details" label="具体描述"></el-table-column>
                </el-table>

                <!-- 总分 -->
                <h4>总分: {{ totalPoints }}</h4>

                <el-dialog :visible.sync="dialog">
                    <p>用户信息:</p>
                    <p>姓名:{{ userInfo.account }}</p>
                    <p>姓名:{{ userInfo.name }}</p>
                    <p>身份证号码：{{ userInfo.idCard}}</p>
                    <p>性别：{{ userInfo.gender }}</p>
                    <p>年龄：{{ userInfo.age }}</p>
                    <p>用户地址：{{ userInfo.address }}</p>
                    <p>邮箱：{{ userInfo.email }}</p>
                    <p>手机号：{{ userInfo.phone }}</p>
                    <p>银行：{{ userInfo.bank }}</p>
                    <p>银行卡号：{{ userInfo.bankCardNumber }}</p>
                    <p>关联人信息:</p>
                    <hr>
                    <h3>求助人的信息：</h3>
                    <p>姓名: {{ person.personName }}</p>
                    <p>性别：{{ person.personGender }}</p>
                    <p>年龄：{{ person.personAge }}</p>
                    <p>关系：{{ person.personRelationship}}</p>
                    <p>手机号：{{ person.personPhone }}</p>
                    <p>身份证号码：{{ person.personIdCard }}</p>
                    <el-button type="primary" @click="download">文件下载</el-button>
                    <el-button type="primary" @click="completeInfoReview">个人信息审查完毕</el-button>
                </el-dialog>
                <!-- 募捐申请评价对话框 -->
                <el-dialog :visible.sync="evaluationDialogVisible" title="募捐申请评价">
                    <template>
                        <el-form :model="formData">
                          <el-form-item label="状态">
                            <el-select v-model="formData.status">
                              <el-option label="通过" value="通过"></el-option>
                              <el-option label="驳回" value="驳回"></el-option>
                            </el-select>
                          </el-form-item>
                      
                          <el-form-item label="建议金额" required>
                            <el-input-number v-model="formData.donationAmount" :min="0"></el-input-number>
                          </el-form-item>
                      
                          <el-form-item label="原因" required>
                            <el-input type="textarea" v-model="formData.message"></el-input>
                          </el-form-item>
                      
                          <el-form-item>
                            <el-button type="primary" @click="submitEvaluate">提交</el-button>
                            <el-button type="default" @click="cancelEvaluate">取消</el-button>
                          </el-form-item>
                        </el-form>
                      </template>                      
                    </form>
                </el-dialog>

                <el-row class="flex-container">
                    <el-row class="number" :gutter="20">
                        <el-col>
                            <div class="box">募捐目标:<br><br><br><span class="large-font">{{ donationDetails[0] ?
                                    donationDetails[0].donationAmount : '' }}</span></div>
                        </el-col>
                        <el-col>
                            <el-button class="box" @click="fetchDonationRecords">
                                已募捐金额:<br><br><br>
                                <span class="large-font">{{ donationDetails[0] ? donationDetails[0].donatedAmount : ''
                                    }}</span>
                            </el-button>
                        </el-col>
                        <el-col>
                            <div class="box">募捐截止时间:<br><br><br><span class="large-font">{{ donationDetails[0] ?
                                    donationDetails[0].deadline : '' }}</span></div>
                        </el-col>
                        <el-col>
                            <el-button class="box" @click="fetchFundingDetails">
                                已拨款金额:<br><br><br>
                                <span class="large-font">{{ donationDetails[0] ? donationDetails[0].expenseAmount:
                                    ''}}</span>
                            </el-button>
                        </el-col>
                    </el-row>

                    <el-row class="buttons">
                        <el-col>
                            <el-button type="primary" icon="el-icon-s-operation" @click="downloadDataTemplate">
                                下载募捐资料模板
                            </el-button>

                            <el-button type="primary" icon="el-icon-download" @click="getdonationIdFile">
                                下载募捐证明
                            </el-button>
                        </el-col>
                    </el-row>

                </el-row>
                <el-col v-if="isTableVisible">
                    <el-table :data="donationRecords">
                        <el-table-column prop="donationRecordsId" label="募捐单号"></el-table-column>
                        <el-table-column prop="userId" label="募捐人">
                            <template slot-scope="scope">
                                用户{{ scope.row.userId}}号
                            </template>
                        </el-table-column>
                        <el-table-column prop="donationTime" label="捐款时间"></el-table-column>
                        <el-table-column prop="donationAmount" label="捐款金额"></el-table-column>
                    </el-table>
                </el-col>
                <el-col v-if=" isExpenseTableVisible">
                    <el-table :data="fundingDetails">
                        <el-table-column prop="requestMoneyId" label="拨款单号"></el-table-column>
                        <el-table-column prop="money" label="申请金额"></el-table-column>
                        <el-table-column prop="time" label="拨款时间"></el-table-column>
                        <el-table-column prop="reason" label="拨款原因"></el-table-column>
                        <el-table-column label="操作">
                            <template slot-scope="scope">
                                <div>
                                    <el-button @click="downloadFile(scope.row)">下载文件</el-button>
                                </div>
                            </template>
                        </el-table-column>

                    </el-table>
                </el-col>
            </el-card>

        </div>
        <script>
            
            var requestId = localStorage.getItem('requestId');
            var userId = localStorage.getItem('userId');
            var donationIds = JSON.parse(localStorage.getItem("donationIds"));
            var DonationId = localStorage.getItem('donationId');
            var index = localStorage.getItem('index');
            new Vue({
                el: '#app',
                data() {
                   
                    return {
                        formData: {
                            requestId: "",
                            userId: "",
                            donationAmount: '',
                            message: '',
                            status: '通过'
                        },
                        
                        evaluationDialogVisible: false,
                        personsId: "",
                        person: {}, // 存储表格数据
                        userInfo: {}, // 存储表格数据
                        isPointsRules: "",
                        pointsList: [], // 积分列表数据
                        selectedRows: [], // 选择的行数据
                        userId: '',
                        isExpenseTableVisible: false,
                        isTableVisible: false,
                        donationDetails: [],
                        donationsInfo: null,
                        donationRecords: [],
                        fundingDetails: [],
                        dialogVisible: false,
                        dialog: false,
                        donationForm: {
                            amount: ''
                        }
                    }
                },
                mounted() {
                    this.currentUser = localStorage.getItem('userId');
                },
                methods: {
                    //个人信息审核完毕
                    save() {
                        var userRole = parseInt(localStorage.getItem('userRole'))
                        if (userRole === 1) {
                            window.location.href = "../manageFuncation/suggestByRequest.html"
                        }
                        else {
                            window.location.href = "../rootManageFunction/replyByRequest.html"
                        }
                    },
                    goToPreviousPage() {
                        if (parseInt(index) === 0) {
                            this.$message.error('已经到第一页了！')
                            return;
                        } else {
                            localStorage.setItem("donationId", donationIds[parseInt(index) - 1]);
                            localStorage.setItem("index", parseInt(index) - 1);
                            location.reload();
                        }
                        // 上一页的逻辑处理代码
                    },
                    goToNextPage() {

                        if (parseInt(index) === donationIds.length - 1) {
                            this.$message.error('已经到最后一页了！')
                            return;
                        }
                        else {
                            console.log(donationIds);
                            localStorage.setItem("donationId", donationIds[parseInt(index) + 1]);
                            localStorage.setItem("index", parseInt(index) + 1);
                            location.reload();
                        }
                        // 上一页的逻辑处理代码
                    },
                    //
                    completeInfoReview() {
                        this.dialog = false;
                    },
                    //评价想相关的代码
                    submitEvaluate: function () {
                        event.preventDefault()
                        this.formData.userId = userId;
                        this.formData.requestId = requestId;
                          fetch("http://localhost:8888/api/evaluate/addByRequestId", {
                            method: "POST",
                            headers: {
                                "Content-Type": "application/json"
                            },
                            body: JSON.stringify(this.formData)
                        })
                            .then(response => response.json())
                            .then(data => {
                                if (data.code === 0) {
                                    this.$message.success(data.message);
                                } else {
                                    this.$message.error(data.message);
                                }
                                console.log(data);
                            })
                            .catch(error => {
                                console.error(error);
                            });
                            this.evaluationDialogVisible=false;  
                    },
                    cancelEvaluate(){
                        this.evaluationDialogVisible=false;
                    },
                    openEvaluationDialog() {
                        this.evaluationDialogVisible = true;
                    },
                    //下载个人资料
                    download() {
                        axios({
                            method: 'get',
                            url: 'http://localhost:8888/api/persons/download',
                            params: {
                                personId: this.person.personId
                            },
                            responseType: 'arraybuffer'  // 设置响应类型为 arraybuffer，用于处理二进制数据
                        }).then(response => {
                            const blob = new Blob([response.data], { type: 'application/octet-stream' });
                            const url = window.URL.createObjectURL(blob);
                            const link = document.createElement('a');
                            link.href = url;
                            link.setAttribute('download', 'personFile.pdf');
                            document.body.appendChild(link);
                            link.click();
                            document.body.removeChild(link);
                        }).catch(error => {
                            this.$message.error("文件不存在")
                            
                            console.error('Error downloading file:', error);
                            // 处理下载失败的情况
                        });
                    },
                    showTable() {
                        this.dialog = true
                        axios.get('http://localhost:8888/api/persons/getPerson', {
                            params: {
                                personsId: this.personsId// 替换为实际的pointsId值
                            }
                        })
                            .then(response => {
                                const result = response.data;
                                if (result.code === 0) {
                                    this.person = result.data;
                                    this.getuserInfo()
                                } else {
                                    console.error(result.message);
                                    console.log("查询失败");
                                }
                            })
                            .catch(error => {
                                console.error(error);
                                // 处理错误的逻辑...
                            });
                    },
                    getuserInfo() {
                        axios.get('http://localhost:8888/api/user/getUserInfoVo', {
                            params: {
                                userId: this.person.userId// 替换为实际的pointsId值
                            }
                        })
                            .then(response => {
                                const result = response.data;
                                if (result.code === 0) {
                                    this.userInfo = result.data;
                                } else {
                                    console.error(result.message);
                                    console.log("查询失败");
                                }
                            })
                            .catch(error => {
                                console.error(error);
                                // 处理错误的逻辑...
                            });
                    },
                    search() {
                        // alert(this.isPointsRules)
                        axios.get('http://localhost:8888/api/donation/getByIsPointsRules', {
                            params: {
                                isPointsRules: this.isPointsRules// 替换为实际的pointsId值
                            }
                        })
                            .then(response => {
                                const result = response.data;
                                if (result.code === 0) {
                                    this.pointsList = result.data;
                                } else {
                                    console.error(result.message);
                                    console.log("查询失败");
                                }
                            })
                            .catch(error => {
                                console.error(error);
                                // 处理错误的逻辑...
                            });
                    },
                    //获取募捐详情
                    getDonationDetails() {
                        axios.get('http://localhost:8888/api/donation/get', {
                            params: {
                                donationId: DonationId
                            }
                        })
                            .then(response => {
                              
                             
                                this.personsId = response.data.data.personId
                                this.isPointsRules = response.data.data.isPointsRules
                                data = response.data.data
                                if (data.deadline) {
                                    data.deadline = new Date(data.deadline).toLocaleDateString(); // 格式化为年月日
                                }
                                this.donationDetails.push(data);
                                this.search()
                            })
                            .catch(error => {
                                console.error(error);
                            });
                        axios.get('http://localhost:8888/api/donation/getDonationsInfo', {
                            params: {
                                donationId: DonationId
                            }
                        })
                            .then(response => {
                                if (response.data.code === 0) {
                                    this.donationsInfo = response.data.data;
                                } else {
                                    console.error('Request failed: ' + response.data.message);
                                }
                            })
                            .catch(error => {
                                console.error('Request error: ' + error);
                            });
                    },
                    // 获取捐赠记录
                    fetchDonationRecords() {
                        if (this.isTableVisible) {
                            this.isTableVisible = false;
                            return;
                        }

                        axios.get('http://localhost:8888/api/donation/getDonationRecords', {
                            params: {
                                donationId: DonationId
                            }
                        })
                            .then(response => {
                                if (response.data.code === 0) {
                                    this.donationRecords = response.data.data;
                                    this.isTableVisible = true;

                                    this.donationRecords = this.donationRecords.map(record => {
                                        if (record.donationTime) {
                                            let donationTime = new Date(record.donationTime);
                                            record.donationTime = donationTime.toLocaleDateString(); // 格式化为年月日
                                        }
                                        return record;
                                    });


                                } else {
                                    console.error('查询失败:', response.data.message);
                                }
                            })
                            .catch(error => {
                                console.error('请求失败:', error);
                            });
                    },
                    //拨款详情
                    fetchFundingDetails() {
                        if (this.isExpenseTableVisible) {
                            this.isExpenseTableVisible = false;
                            return;
                        }
                        axios.get('http://localhost:8888/api/funding/queryByDonationId', {
                            params: {
                                donationId: DonationId, // 这里替换为实际的募捐活动 ID
                                isPerson: 0 // 这里替换为实际的是否为本人的值
                            }
                        })
                            .then(response => {
                                if (response.data.code === 0) {
                                    this.fundingDetails = response.data.data;
                                    this.isExpenseTableVisible = true;
                                    this.fundingDetails = this.fundingDetails.map(record => {
                                        if (record.time) {
                                            let time = new Date(record.time);
                                            record.time = time.toLocaleDateString(); // 格式化为年月日
                                        }
                                        return record;
                                    });
                                } else {
                                    console.error('查询失败:', response.data.message);
                                }
                            })
                            .catch(error => {
                                console.error('请求失败:', error);
                            });
                    },
                    //下载拨款文件
                    downloadFile(row) {
                        const fundingId = row.requestMoneyId; // 这里的fundingId应该根据实际情况获取
                        // 构建查询参数对象
                        const params = new URLSearchParams();
                        params.append('fundingId', fundingId);

                        axios.get(
                            'http://localhost:8888/api/funding/downloadReport',
                            {
                                params: params
                            },
                            'blob' // 表明返回服务器返回的数据类型
                        )
                            .then((response) => {
                                const url = window.URL.createObjectURL(new Blob([response.data]));
                                const link = document.createElement('a');
                                link.href = url;
                                link.setAttribute('download', '用钱报告.pdf');
                                document.body.appendChild(link);
                                link.click();
                            })
                            .catch((error) => {
                                console.log(error);
                            });
                    },
                    //下载募捐资料
                    getdonationIdFile() {
                        fetch(`http://localhost:8888/api/donation/downloadData?donationId=${DonationId}`)
                            .then(response => response.blob())
                            .then(blob => {
                                const url = window.URL.createObjectURL(blob);
                                const link = document.createElement('a');
                                link.href = url;
                                link.setAttribute('download', 'dontionFile.pdf');
                                document.body.appendChild(link);
                                link.click();
                                document.body.removeChild(link);
                            })
                            .catch(error => {
                                this.$message.error("文件不存在")
                                console.error('Error downloading file:', error);
                                // 处理下载失败的情况
                            });
                    },
                    //下载募捐资料模板
                    downloadDataTemplate() {
                        axios({
                            method: 'get',
                            url: 'http://localhost:8888/api/donation/downloadDataTemplate',
                            responseType: 'blob' // 指定响应类型为二进制数据
                        })
                            .then((response) => {
                                const url = window.URL.createObjectURL(new Blob([response.data]));
                                const link = document.createElement('a');
                                link.href = url;
                                link.setAttribute('download', 'donation_template.doc'); // 指定下载文件的名称，根据实际情况修改后缀名
                                document.body.appendChild(link);
                                link.click();
                            })
                            .catch((error) => {
                                console.error('下载文件时出现错误：', error);
                            });
                    },


                },
                created() {
                    // 创建一个Promise链
                    Promise.resolve()
                    // 第一个任务：调用getDonationDetails函数
                    return this.getDonationDetails();
                },
                computed: {
                    totalPoints() {
                        return this.pointsList.reduce((total, item) => total + item.pointsValue, 0);
                    },
                },
        
                

            });
        </script>
    </body>

</html>